    //
//  TutorListViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/20.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "TutorListViewController.h"
#import "TutorListTableViewCell.h"
#import "ButtonTableViewCell.h"

#import "DrivateTutorDetailViewController.h"

static NSString *CellIdentifier = @"TutorListTableViewCell";
static NSString *buttonCellIdentifier = @"ButtonTableViewCell";

@interface TutorListViewController ()
<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UIView *buttonView;
@property (strong, nonatomic) IBOutlet UIButton *LeftButton;
@property (strong, nonatomic) IBOutlet UIButton *LeftImage;
@property (strong, nonatomic) IBOutlet UIButton *rightButton;
@property (strong, nonatomic) IBOutlet UIButton *rightImage;
@property (strong, nonatomic) IBOutlet UITableView *tableview;


@property (strong, nonatomic) IBOutlet UITableView *buttonTableview;
@property (strong, nonatomic) IBOutlet UIButton *backButton;

@property (strong, nonatomic) NSMutableArray *TutorListArray;


@property (strong, nonatomic) NSArray *left;
@property (strong, nonatomic) NSArray *right;
@property (weak, nonatomic) IBOutlet UITextField *searchField;

@end

@implementation TutorListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.LeftButton setTitle:[NSString stringWithFormat:@"%@",self.leftArray[self.leftCount][@"mlagName"]] forState:UIControlStateNormal];
    [self.rightButton setTitle:[NSString stringWithFormat:@"%@",self.rightArray[self.rightCount][@"mlsuName"]] forState:UIControlStateNormal];
    [self.tableview.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _TutorListArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    [self adaptiveViewLayout:self.buttonView];
    _scroview.contentSize = flexibleSize(CGSizeMake(0, 505), NO);
    
    _searchField.layer.cornerRadius = 4*VerticalRatio();
    _searchField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 1)];
    _searchField.leftViewMode = UITextFieldViewModeAlways;
    
    
    [self.tableview registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    
    [self.buttonTableview registerNib:[UINib nibWithNibName:buttonCellIdentifier bundle:nil] forCellReuseIdentifier:buttonCellIdentifier];
    self.buttonTableview.hidden = YES;
    self.buttonTableview.delegate = self;
    self.buttonTableview.dataSource = self;
    
    self.searchField.delegate = self;
    
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableview.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self TutorList];
        });
        
    }];
    // 马上进入刷新状态
    [self.tableview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{

    if (_TutorListArray.count == _totle) {
        [self.tableview.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self TutorList];
        });
    }
    
}


#pragma mark ==== UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    [self.tableview.header beginRefreshing];
    return YES;
}

#pragma mark - 查询家教列表
- (void)TutorList {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    if (_searchStr) {
        [dic setObject:_searchStr forKey:@"mexpName"];
    }
    if (_searchField.text.length>0) {
        [dic setObject:_searchField.text forKey:@"mexpName"];
    }
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    if (_leftCount && _leftCount != 0) {
        [dic setObject:_leftArray[_leftCount][@"mlagId"] forKey:@"mexpAgeIds"];
    }
    if (_rightCount && _rightCount != 0) {
        [dic setObject:_rightArray[_rightCount][@"mlsuId"] forKey:@"mexpSubjectIds"];
    }

    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallExpertList withHttpType:@"POST" withTag:JY_JY_mallExpertList];
}



- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark - 隐藏buttonTableview
- (IBAction)backButton:(id)sender {
    self.buttonTableview.hidden = YES;
    self.backButton.hidden = YES;
    _LeftButton.selected = NO;
    _LeftImage.selected = NO;
    _rightButton.selected = NO;
    _rightImage.selected = NO;
}

#pragma mark - 阶段/科目
- (IBAction)button:(UIButton *)sender {
    
    if (sender == _LeftButton) {
        
        if (_LeftButton.selected) {
            _LeftButton.selected = NO;
            _LeftImage.selected = NO;
        } else {
            _LeftButton.selected = YES;
            _LeftImage.selected = YES;
        }
        _rightButton.selected = NO;
        _rightImage.selected = NO;
        
        self.buttonTableview.hidden = !_LeftButton.selected;
        self.buttonTableview.frame = flexibleFrame(CGRectMake(0, 40, 320, 48*(self.leftArray.count)), NO);
        
        self.backButton.hidden = !_LeftButton.selected;
        
        [self.buttonTableview reloadData];
        
    } else if (sender == _rightButton) {
        
        if (_rightButton.selected) {
            _rightButton.selected = NO;
            _rightImage.selected = NO;
        } else {
            _rightButton.selected = YES;
            _rightImage.selected = YES;
        }
        _LeftButton.selected = NO;
        _LeftImage.selected = NO;
        
        self.buttonTableview.hidden = !_rightButton.selected;
        self.buttonTableview.frame = flexibleFrame(CGRectMake(0, 40, 320, 48*(self.rightArray.count)), NO);
        
        self.backButton.hidden = !_rightButton.selected;
        
        [self.buttonTableview reloadData];
    }
    
}

#pragma mark - 搜索
- (IBAction)search:(id)sender {
    if (_searchField.hidden == YES) {
        _searchField.hidden = NO;
    }else{
        if (_searchField.text.length>0) {
            [self.tableview.header beginRefreshing];
        }else{
            _searchField.hidden = YES;
        }
    }
}


#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableview) {
        return self.TutorListArray.count;
    } else {
        
        if (self.LeftButton.selected) {
            return self.leftArray.count;
        } else {
            return self.rightArray.count;
        }
    }
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableview) {
        
        return 85*VerticalRatio();
    } else {
        
    return 48*VerticalRatio();
    }
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.tableview) {
        TutorListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell= [[TutorListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
        }
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        
        NSString *image = [NSString stringWithFormat:@"%@",self.TutorListArray[indexPath.row][@"mexpImage"]];
        if (image && image.length>0 && ![self.TutorListArray[indexPath.row][@"mexpImage"] isEqual:[NSNull null]]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.TutorListArray[indexPath.row][@"mexpName"]];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@/小时",self.TutorListArray[indexPath.row][@"mexpPrice"]];
        NSArray *mallLecturerSubjects = self.TutorListArray[indexPath.row][@"mallLecturerSubjects"];
        NSString *mlsuName;
        for (int i = 0; i < mallLecturerSubjects.count; i++) {
            if (i == 0) {
                mlsuName = [NSString stringWithFormat:@"%@",mallLecturerSubjects[i][@"mlsuName"]];
            } else {
                mlsuName = [NSString stringWithFormat:@"%@%@",mlsuName,mallLecturerSubjects[i][@"mlsuName"]];
            }
        }
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",mlsuName];
        CGFloat distance = [self.TutorListArray[indexPath.row][@"distance"]floatValue];
        if (distance<1000) {
            [cell.distanceButton setTitle:[NSString stringWithFormat:@" 距离%dm",(NSInteger)distance] forState:UIControlStateNormal];
        }else{
         [cell.distanceButton setTitle:[NSString stringWithFormat:@" 距离%.1fkm",distance/1000] forState:UIControlStateNormal];
        }
        
        
        return cell;
        
    } else {
        ButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:buttonCellIdentifier];
        if (!cell) {
            cell = [[ButtonTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:buttonCellIdentifier];
        }
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        
        
        cell.label.textColor = [UIColor colorWithWhite:0.243 alpha:1.000];
        cell.image.image = [UIImage imageNamed:@"TutorList4"];
        
        if (self.LeftButton.selected) {
            cell.label.text = self.leftArray[indexPath.row][@"mlagName"];
            if (_leftCount == indexPath.row) {
                cell.label.textColor = [UIColor colorWithRed:0.086 green:0.306 blue:0.529 alpha:1.000];
                cell.image.image = [UIImage imageNamed:@"TutorList5"];
            }
            
        } else {
            cell.label.text = self.rightArray[indexPath.row][@"mlsuName"];
            if (_rightCount == indexPath.row) {
                cell.label.textColor = [UIColor colorWithRed:0.086 green:0.306 blue:0.529 alpha:1.000];
                cell.image.image = [UIImage imageNamed:@"TutorList5"];
            }
        }
        
        return cell;
    }

}


//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.buttonTableview) {
        self.buttonTableview.hidden = YES;
        self.backButton.hidden = YES;
        
        if (self.LeftButton.selected) {
            
            self.leftCount = indexPath.row;
            _LeftButton.selected = NO;
            _LeftImage.selected = NO;
            [self.LeftButton setTitle:[NSString stringWithFormat:@"%@",self.leftArray[self.leftCount][@"mlagName"]] forState:UIControlStateNormal];
            
        } else {
            
            self.rightCount = indexPath.row;
            _rightButton.selected = NO;
            _rightImage.selected = NO;
            [self.rightButton setTitle:[NSString stringWithFormat:@"%@",self.rightArray[self.rightCount][@"mlsuName"]] forState:UIControlStateNormal];
        }
        
        [self.tableview.header beginRefreshing];
        [tableView reloadData];
        
    } else {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
        DrivateTutorDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"DrivateTutorDetail"];
        
        page.mexpId = _TutorListArray[indexPath.row][@"mexpId"];
        page.backBlock = ^(){};
        [[Common getNavigation] pushViewController:page];
    }
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableview.header endRefreshing];
    [_tableview.footer endRefreshing];
    if (tag==JY_JY_mallExpertList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableview.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableview.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.TutorListArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.TutorListArray addObject:entity];
                }
                [_tableview reloadData];
                
            });
            

            [self.buttonTableview reloadData];
        }
        
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableview.header endRefreshing];
    [_tableview.footer endRefreshing];
    [self dismissWaitDialog];
    
    
}











@end
